iT邦幫忙

2021 iThome 鐵人賽

DAY 18
0
自我挑戰組

用unity製作2DRPG雛形-沒有大野狼的小紅帽系列 第 18

18.unity實例化(上)(Instantiate)

  • 分享至 

  • xImage
  •  

Instantiate實例化,用於將物件生成至場景中。(參考unity手冊)

適合用在複製一樣的物件,大量生成。這一次主要是想用實例化來生成蘋果,在場中自動放很多顆蘋果!!

先來看定義

//宣告建構式
public static Object Instantiate(Object original);
public static Object Instantiate(Object original, Transform parent);
public static 
Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
  • Object original :生成物件,要複製的Object,可以是GameObject也可以是UI或其他物件。
  • Transform parent:父物件(parent),會將生成物件設定為該物件的子物件(child)。
  • bool instantiateInWorldSpace:當生成於父物件底下時,可以選擇依照世界座標(true)還是父物件座標(false)生成。
  • Vector3 position:Position for the new object. 設置Position,生成於此位置座標。
  • Quaternion rotation:Orientation of the new object. 設置Rotation,生成於此旋轉角度。

※沒有要旋轉的時候,旋轉向量可以填這個:Quaternion.identity

實際例子1-生成

1.先創建好要複製的物件
1.png

2.寫好腳本,掛在空物件上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InstantiateApple : MonoBehaviour
{   
    //宣告生成物件
    public GameObject apple;
    //設置三個生成位置
    Vector3 position1 = new Vector3(-1.039978f,-0.330002f,0.0f);
    Vector3 position2 = new Vector3(-0.039978f,-1.330002f,0.0f);
    Vector3 position3 = new Vector3(-0.039978f,-0.330002f,0.0f);
	//設置旋轉
	Quaternion rotation1 = new Quaternion(0,0,0,0);

    void Start()
    {   
        Instantiate(apple,position1, rotation1);
        Instantiate(apple,position2, new Quaternion(0,0,0,0));
        Instantiate(apple,position3, Quaternion.identity);

    }

掛完腳本之後記得將要複製的物件拖曳進去。

3.設定好之後執行
2.png

實際例子2-整理至父物件

1.做法都一樣,改腳本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InstantiateApple : MonoBehaviour
{   
    //宣告要生成的物件
    public GameObject apple;
    //宣告生成物件的父物件
    public Transform appleClass;
    //三個生成位置
    Vector3 position1 = new Vector3(-1.039978f,-0.330002f,0.0f);
    Vector3 position2 = new Vector3(-0.039978f,-1.330002f,0.0f);
    Vector3 position3 = new Vector3(-0.039978f,-0.330002f,0.0f);
	//設置旋轉
    Quaternion rotation1 = new Quaternion(0,0,0,0);

    void Start()
    {   
        Instantiate(apple,position1, rotation1,appleClass);
        Instantiate(apple,position2, new Quaternion(0,0,0,0),appleClass);
        Instantiate(apple,position3, Quaternion.identity,appleClass);

    }
}

2.結果
3.png


上一篇
17.unity顯示/隱藏物件(SetActive)
下一篇
19.unity實例化(下)(Random、迴圈、Prefab)
系列文
用unity製作2DRPG雛形-沒有大野狼的小紅帽30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言